const db = uniCloud.database();

exports.main = async (event, context) => {
  const { data = {} } = event;
  const { page = 1, pageSize = 20 } = data;
  
  let uid = context.auth && context.auth.uid;
  let userRole = context.auth?.role || [];
  
  // 如果 context.auth 为空，尝试从 event 中获取 token 并手动验证
  if (!uid && event.uniIdToken) {
    try {
      const jwtToken = require('jsonwebtoken');
      const decoded = jwtToken.decode(event.uniIdToken);
      if (decoded && decoded.uid) {
        uid = decoded.uid;
        userRole = decoded.role || [];
      }
    } catch (err) {
      // token 解析失败，继续
    }
  }

  if (!uid) {
    return {
      code: 401,
      message: '未授权',
      data: null
    };
  }

  try {
    const skip = (Number(page) - 1) * Number(pageSize);
    let query = db.collection('food-order');
    
    // 如果是厨师，可以查看所有订单；否则只能查看自己的订单
    if (!userRole.includes('chef')) {
      query = query.where({
        user_id: uid
      });
    }
    
    // 查询订单
    const { data: ordersList, count } = await query
      .orderBy('create_date', 'desc')
      .skip(skip)
      .limit(Number(pageSize))
      .get();

    console.log('查询返回的订单数据:', JSON.stringify(ordersList, null, 2))

    return {
      code: 200,
      message: '成功',
      data: {
        list: ordersList,
        totalPages: Math.ceil(count / Number(pageSize)),
        page: Number(page),
        pageSize: Number(pageSize)
      }
    };
  } catch (err) {
    return {
      code: 500,
      message: err.message,
      data: null
    };
  }
};
